﻿using System;
using System.Drawing;

namespace ShpViewer
{
    class Polygon
    {
        public double[] box;
        public int numParts;
        public int numPoints;
        public int[] parts;
        public PointF[] points;

        public Polygon()
        {}

        public void Read(ExtendBinaryReader extendBinaryReader)
        {
            int recordNumber = extendBinaryReader.ReadInt32UsingBigEndian();
            int recordLength = extendBinaryReader.ReadInt32UsingBigEndian();
            int recordShapeType = extendBinaryReader.ReadInt32();
            this.box = new Double[4];
            this.box[0] = extendBinaryReader.ReadDouble();
            this.box[1] = extendBinaryReader.ReadDouble();
            this.box[2] = extendBinaryReader.ReadDouble();
            this.box[3] = extendBinaryReader.ReadDouble();
             this.numParts = extendBinaryReader.ReadInt32();
            this.numPoints = extendBinaryReader.ReadInt32();
            this.parts = new int[this.numParts];
            for (int i = 0; i < this.numParts; i++)
            {
                this.parts[i] = extendBinaryReader.ReadInt32();
            }
            this.points = new PointF[this.numPoints];
            for (int i = 0; i < this.numPoints; i++)
            {
                this.points[i].X = (float)extendBinaryReader.ReadDouble();
                this.points[i].Y = (float)extendBinaryReader.ReadDouble();
                this.points[i].Y = 0 - this.points[i].Y;
            }
        }

        public void Render(Graphics g, double xMin, double yMax, float scaleX, float scaleY)
        {
            int m = 0;
            for (int j = 1; j < this.parts.Length + 1; j++)
            {
                int length;
                if (j != this.parts.Length)
                {
                    length = this.parts[j] - this.parts[j - 1];
                }
                else
                {
                    length = this.points.Length - this.parts[j - 1];
                }
                PointF[] pt = new PointF[length];
                for (int k = 0; k < length; k++)
                {
                    pt[k].X = (this.points[m].X - (float)xMin) * scaleX;
                    pt[k].Y = (this.points[m].Y - (float)yMax) * scaleY;
                    m++;
                }
                g.DrawPolygon(Pens.Black, pt);
            }
        }
    }
}
